# -*- coding: utf-8 -*-
import urllib,urllib2, cookielib,re
from datetime import datetime
from win32com.client import Dispatch
import Image,ImageFilter,ImageEnhance
import time
import StringIO
import os,sys
import json

def code(req):
	while True:
		pic=urllib2.urlopen(req).read()
		# pic_name="old.jpg"
		# f = open(pic_name, 'wb')
		# f.write(pic)
		# f.close
		# time.sleep(5)
		box=(5,5,95,30)
		im=StringIO.StringIO(pic)
		# im.save(pic_name)
		im=Image.open(im)
		im=im.crop(box)
		im=im.filter(ImageFilter.MedianFilter())
		enhancer = ImageEnhance.Contrast(im)
		im = enhancer.enhance(2)
		im = im.convert('L')
		# im.show()
		im.save("code.jpg")

		os.popen('tesseract.exe code.jpg code') 
		t=open('code.txt').read()
		# print "txt:",t
		pattern=r'[A-Z0-9]'
		t=re.findall(pattern,t)
		if(len(t)==4):
			return "".join(t)
		# print "check:","".join(t)
	
# ##########################################	
# 主程序开始
# ##########################################
# 定义查询的日期		
# 定义更新的报关单数量
# 使用cookie
cookie_support= urllib2.HTTPCookieProcessor(cookielib.CookieJar())
opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler)
urllib2.install_opener(opener)
# 登录信息
pic_req=urllib2.Request(url ="http://www.zjetc.net/Home/GetCheckCode")
# print code(pic_req)
login_post_data=urllib.urlencode({
	'cboLoginType':'1',
	'txtUserNo':'13986',
	'txtPassWord':'111111',
	'txtChcekCode':code(pic_req),
	'login':'yes'
})
# 登录的地址
login_req = urllib2.Request(
	url = 'http://www.zjetc.net/Home/Login',
	data = login_post_data
)
login_result = urllib2.urlopen(login_req).read()
j=json.loads(login_result)
print j
if(j['STATE']=='OK'):
	print 'ok'
	# 这个内容没什么用
	# print urllib2.urlopen('http://www.zjetc.net/Accounts/CustomerInfo').read()
